"use strict";
let date_format = function (timestamp, format) {
   format = format || 'yyyy年MM月dd';
   timestamp = timestamp + "";
   if (timestamp * 1 > 0 && timestamp.length == 10) {
      timestamp = timestamp * 1000;
   }

   // 通过getDate()方法获取date类型的时间
   let regYear = new RegExp("(y+)", "i");
   let realDate = new Date(timestamp);

   function timeFormat(num) {
      return num < 10 ? '0' + num : num;
   }

   let date = [["M+", timeFormat(realDate.getMonth() + 1)], ["d+", timeFormat(realDate.getDate())], ["h+", timeFormat(realDate.getHours())], ["m+", timeFormat(realDate.getMinutes())], ["s+", timeFormat(realDate.getSeconds())], ["q+", Math.floor((realDate.getMonth() + 3) / 3)], ["S+", realDate.getMilliseconds()],];
   let reg1 = regYear.exec(format);
   if (reg1) {
      format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length));
   }

   for (let i = 0; i < date.length; i++) {
      let k = date[i][0];
      let v = date[i][1];
      // getRegExp初始化一个正则表达式对象
      let reg2 = new RegExp("(" + k + ")").exec(format);
      if (reg2) {
         format = format.replace(reg2[1], reg2[1].length == 1 ? v : ("00" + v).substring(("" + v).length));
      }
   }
   return format;
};

layui.define(["layer"], function (exprots) {
   let $ = layui.jquery;
   let okUtils = {
      /**
       * 是否前后端分离
       */
      isFrontendBackendSeparate: false,

      /**
       * 服务器地址
       */
      baseUrl: "",

      /**
       * 获取body的总宽度
       */
      getBodyWidth: function () {
         return document.body.scrollWidth;
      },

      /**
       * 主要用于对ECharts视图自动适应宽度
       */
      echartsResize: function (element) {
         element = element || [];
         window.addEventListener("resize", function () {
            let isResize = localStorage.getItem("isResize");
            for (let i = 0; i < element.length; i++) {
               element[i].resize();
            }
         });
      },

      /**
       * ajax()函数二次封装
       * @param url
       * @param type
       * @param params
       * @param load
       * @returns {*|never|{always, promise, state, then}}
       */
      ajax: function (url, type, params, load) {
         let deferred = $.Deferred();
         let loadIndex;
         $.ajax({
            url: okUtils.isFrontendBackendSeparate ? okUtils.baseUrl + url : url,
            type: type || "get",
            data: params || {},
            dataType: "json",
            beforeSend: function () {
               if (load) {
                  loadIndex = layer.load(0, {shade: 0.3});
               }
            },
            success: function (data) {
               if (data.statusCode == 200) {
                  // 业务正常
                  deferred.resolve(data)
               } else {
                  // 业务异常
                  layer.msg(data.msg, {icon: 7, time: 2000});
                  deferred.reject("okUtils.ajax warn: " + data.message);
               }
            },
            complete: function () {
               if (load) {
                  layer.close(loadIndex);
               }
            },
            error: function () {
               layer.close(loadIndex);
               layer.msg("服务器错误", {icon: 2, time: 2000});
               deferred.reject("okUtils.ajax error: 服务器错误");
            }
         });
         return deferred.promise();
      },

      /**
       * 主要用于针对表格批量操作操作之前的检查
       * @param table
       * @returns {string}
       */
      tableBatchCheck: function (table) {
         let checkStatus = table.checkStatus("tableId");
         let rows = checkStatus.data.length;
         if (rows > 0) {
            let idsStr = "";
            for (let i = 0; i < checkStatus.data.length; i++) {
               idsStr += checkStatus.data[i].id + ",";
            }
            return idsStr;
         } else {
            layer.msg("未选择有效数据", {offset: "t", anim: 6});
         }
      },

      /**
       * 在表格页面操作成功后弹窗提示
       * @param content
       */
      tableSuccessMsg: function (content) {
         layer.msg(content, {icon: 1, time: 1000}, function () {
            // 刷新当前页table数据
            $(".layui-laypage-btn")[0].click();
         });
      },

      /**
       * sessionStorage 二次封装
       */
      session: function (name, value) {
         if (value) { /**设置*/
            if (typeof value == "object") {
               sessionStorage.setItem(name, JSON.stringify(value));
            } else {
               sessionStorage.setItem(name, value);
            }
         } else if (null !== value) {
            /**获取*/
            let val = sessionStorage.getItem(name);
            try {
               val = JSON.parse(val);
               return val;
            } catch (err) {
               return val;
            }
         } else { /**清除*/
            return sessionStorage.removeItem(name);
         }
      },

      /**
       * localStorage 二次封装
       */
      local: function (name, value) {
         try {
            if ("undefined" === typeof value) {
               /**获取*/
               let val = localStorage.getItem(name);
               try {
                  val = JSON.parse(val);
                  return val;
               } catch (err) {
                  return val;
               }
            } else if (value == null) {
               /**清除*/
               return localStorage.removeItem(name);
            } else {
               /**设置*/
               if (typeof value == "object") {
                  localStorage.setItem(name, JSON.stringify(value));
               } else {
                  localStorage.setItem(name, value);
               }
            }
         } catch (e) {
         }
      },

      /**
       * 获取父窗体的okTab
       * @returns {string}
       */
      getOkTab: function () {
         return parent.objOkTab;
      },

      /**
       * 格式化当前日期
       * @param date
       * @param fmt
       * @returns {void | string}
       */
      dateFormat: function (date, fmt) {
         date = date || new Date();
         fmt = fmt || "yyyy年M月s日";
         let o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
         };
         if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
         for (let k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
         return fmt;
      },

      number: {
         /**
          * 判断是否为一个正常的数字
          * @param num
          */
         isNumber: function (num) {
            if (num && !isNaN(num)) {
               return true;
            }
            return false;
         },

         /**
          * 判断一个数字是否包括在某个范围
          * @param num
          * @param begin
          * @param end
          */
         isNumberWith: function (num, begin, end) {
            if (this.isNumber(num)) {
               if (num >= begin && num <= end) {
                  return true;
               }
               return false;
            }
         }
      },

      startWith: function (value, str) {
         if (str == null || str == "" || value.length == 0 || str.length > value.length) {
            return false;
         }
         if (value.substr(0, str.length) == str) {
            return true;
         } else {
            return false;
         }
      },

      endWith: function (value, str) {
         if (str == null || str == "" || value.length == 0 || str.length > value.length) {
            return false;
         }
         if (value.substring(value.length - str.length) == str) {
            return true;
         } else {
            return false;
         }
      },

      /**
       * 获取选中树ID值
       * @param num
       * @param begin
       * @param end
       */
      getTreeCheckId: function (data, field) {
         let id = "";
         $.each(data, function (index, item) {
            if (!field || item.field === field) {
               if (id != "") {
                  id = id + "," + item.id;
               } else {
                  id = item.id;
               }
            }
            let i = okUtils.getTreeCheckId(item.children, field);
            if (i != "") {
               id = id + "," + i;
            }
         });
         return id;
      },

      /**
       * 获取选中树ID值
       * @param num
       * @param begin
       * @param end
       */
      zeroFill: function (data, length) {
         data = (data + "");
         if (data.length >= length) {
            return data.substr(0, length);
         } else {
            let len = data.length;
            let diff = length - len + 1;
            if (diff > 0) {
               return Array(diff).join("0") + data;
            }
            return data;
         }
      },

      /**
       * 表默认显示隐藏
       * @param num
       * @param begin
       * @param end
       */
      tableDefaultHide: function (key) {
         try {
            if ("undefined" !== typeof okPapperPageId) {
               let localKey = okPapperPageId + "_" + key;
               let checked = okUtils.local(localKey);
               return checked == null ? false : checked;
            }
         } catch (e) {
         }
         return false;
      }
   };
   exprots("okUtils", okUtils);
});
